package com.weasel.weixin.mp.servlet;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.weasel.weixin.commons.accounts.Oauth2AccessTokenRequest;
import com.weasel.weixin.commons.accounts.Oauth2AccessTokenResponse;
import com.weasel.weixin.mp.builder.MpConfigBuilder;
import com.weasel.weixin.mp.config.MpConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Dylan on 2015/9/28.
 */
public class Oauth2AccessTokenServlet extends HttpServlet {


    public final static Cache<String,Oauth2AccessTokenResponse> cache = CacheBuilder.newBuilder().maximumSize(1).build();


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        MpConfig config = MpConfigBuilder.fromXML("classpath:weixin-config.xml");

        String code = request.getParameter("code");
        String state = request.getParameter("state");

        Oauth2AccessTokenResponse accessTokenResponse = new Oauth2AccessTokenRequest(config).getOauth2AccessToken(code);

        cache.put("oauth2_access_token", accessTokenResponse);

        response.getWriter().println("<h1><a href='/oauth2_userinfo'>页面授权方式获取用户信息</a></h1><br>");
        response.getWriter().println("<h1><a href='/refresh_oauth2'>刷新access_token</a></h1>");
        response.getWriter().flush();
        response.getWriter().close();
    }
}
